'use strict';
let doubanbook = require("doubanbook");//用于解密豆瓣数据

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	
	const db = uniCloud.database();
	
	let {isbn} = event;
	
	let dbResult = await db.collection("isbnlib").where({
		isbn:isbn
	}).get();
	
	if(dbResult.affectedDocs > 0){
		console.log("自己数据库里有")
		return dbResult.data[0];
	}
	//查不到再查豆瓣，否则直接返回数据库里的内容
	console.log("从豆瓣爬取")
	let res = await uniCloud.httpclient.request("https://search.douban.com/book/subject_search?search_text="+isbn,{dataType:"text"});
	
	console.log(res);
	
	let reg = /window\.__DATA__ = "(.*)"/;
	if(reg.test(res.data)){
		let bookdata = RegExp.$1;//获取是一个加密后数据
		let data = doubanbook(bookdata)[0];//解密
		
		
		
		let coverImage = await uniCloud.httpclient.request(data.cover_url);
		let uploadResult = await uniCloud.uploadFile({
			cloudPath:isbn+'.jpg',
			fileContent:coverImage.data
		}) 
		
		let resData = {
			isbn,
			title:data.title,
			cover_url:uploadResult.fileID,//图片url
			abstract:data.abstract
		}
		
		dbResult = await db.collection("isbnlib").add(resData);
		
		resData["_id"] = dbResult["id"]//获取完整id
		
		return resData;
	}
	
	//返回数据给客户端
	return res
};
